#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <threads.h>
#include "Terminal.hpp"

using namespace std;

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    string serverip;
};

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

void *recv_message(void *args)
{
    //OpenTerminal();
    ThreadData* tds = static_cast<ThreadData*>(args);
    char buffer[1024];
    while (true)
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t lenn = sizeof(temp);

        int s = recvfrom(tds->sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &lenn);
        buffer[s] = 0;
        cerr << buffer << endl;
    }
}

void *send_message(void *args)
{
    ThreadData* tds = static_cast<ThreadData*>(args);
    string message;
    socklen_t len = sizeof(tds->server);

    string welcome = tds->serverip + "comming...";
    //sendto(tds->sockfd, welcome.c_str(), welcome.size(), 0, (sockaddr *)&(tds->server), len);
    while (true)
    {
        cout << "Please enter : ";
        getline(cin, message);
        sendto(tds->sockfd, message.c_str(), message.size(), 0, (sockaddr *)&(tds->server), len);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct ThreadData td;

    struct sockaddr_in server;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }

    td.serverip = serverip;

    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);

    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);

    while (true)
    {

    }

    close(td.sockfd);

    return 0;
}